// 南通万科白鹭郡报名邀请H5



// cmd 0 拉去用户数据
// cmd 1 推送用户填写的数据包括自己的微信信息
// cmd 2 后台账号密码登陆
// cmd 3 获得数据表数据


var path = require('path')
var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var validate = utils.validate;
var ip = utils.ip;
var SqlHelper = utils.SqlHelper;
var jwt = require('../../utils/jwt.js')

var getData = function (req, res, next) {
    var body = req.body || req.query;
    var sqlHelper = new SqlHelper('checkin_ntwk_1116');

    if (!body.openid) {
        return res.send({ code: 0, msg: '无效请求, 缺少openid' });
    }
    sqlHelper.select({ openid: body.openid }, (results) => {
        if (results[0]) {
            return res.send({ code: 1, result: results[0] });
        } else {
            return res.send({ code: 0, msg: '您还未注册会员' });
        }
    })
}


var requestList = [];
var canDo = true;

setInterval(function () {
    if (requestList.length > 0 && canDo) {
        canDo = false;
        var obj = requestList.shift();

        var req = obj.req;
        var res = obj.res;
        var token = obj.token;

        pushData(req, res);
    }
}, 500)

var pushData = function (req, res) {

    var body = req.body || req.query;
    var sqlHelper = new SqlHelper('checkin_ntwk_1116');

    if (!body.openid) {
        canDo = true;
        return res.send({ code: 0, msg: '无效请求, 缺少openid' });
    }

    // 信息完整性检查
    if (!validate.isName(body.name) || !validate.isPhone(body.phone)) {
        canDo = true;
        return res.send({ code: 0, msg: '请填写正确的电话和姓名' });
    }
    if (!body.tabletime) {
        canDo = true;
        return res.send({ code: 0, msg: '请选择活动时间' });
    }

    // 数量检查
    var date = new Date()
    var year = date.getYear() - 100 + 2000;
    var mo = date.getMonth() + 1;
    var da = date.getDate()
    var dateStr = year.toString() + mo.toString() + da.toString();

    var query = 'SELECT count(*)num FROM checkin_ntwk_1116 where tableTime = "' + body.tabletime + '"';
    // console.log(body.tableTime);
    sqlHelper.query(query, null, (results) => {
        if (results[0].num >= 12) {
            canDo = true;
            return res.send({ code: 0, msg: body.tabletime + '名额已经达到上限，谢谢您的参与。' });
        } else {
            var data = {
                openid: body.openid,
                name: body.name,
                phone: body.phone,
                tabletime: body.tabletime,
                date: dateStr
            }

            sqlHelper.pushData({ openid: body.openid }, data, (state, results) => {
                canDo = true;
                return res.send({ code: state });
            })

        }
    })

}

var login = async function (req, res, next) {
    var body = req.body || req.query;

    if (!body.account || !body.password) {
        return res.send({ code: 0, msg: '请输入您的账号和密码' });
    }

    if (body.account === "admin" && body.password === "matrixpassword2017") {
        var jwtData = await jwt.encode2(body.account);
        return res.send({ code: 1, token: jwtData.token });
    } else {
        return res.send({ code: 0, msg: '账号密码错误' });
    }

}

// return {list, count, comments}
var getTableData = async function (req, res) {
    var body = req.body || req.query;

    if (!body.token) {
        return res.send({ code: 0, msg: '账号密码错误' });
    }

    try {
        var userid = await jwt.decode(body.token);
        var sqlHelper = new SqlHelper('checkin_ntwk_1116');
        var result = await sqlHelper.asyncSelect(null, body.offset, body.limit);
        var result2 = await sqlHelper.asyncCount() //results[0].num
        var comments = await sqlHelper.asyncComments();
        return res.send({ code: 1, result: { list: result, count: result2[0].num, comments: comments } });
    } catch (error) {
        return res.send({ code: 0, msg: error.message });
    }

}

// 更新用户积分

// var updateUserInfo = async function (req, res) {
//     var body = req.body || req.query;

//     var point = parseInt(body.point);

//     if (!body.token) {
//         return res.send({ code: 0, msg: '账号密码错误' });
//     }
//     if (typeof body.openid != "string") {
//         return res.send({ code: 0, msg: '请指定有效的用户' });
//     }
//     if (typeof point != "number" || isNaN(point)) {
//         return res.send({ code: 0, msg: '请输入正确的数字' });
//     }

//     try {
//         var sqlHelper = new SqlHelper('checkin_ntwk_1116');
//         var results = await sqlHelper.asyncSelect({ id: body.openid });
//         if (results[0]) {
//             var results2 = await sqlHelper.asyncUpdate({ id: body.openid }, { point: body.point });
//             return res.send({ code: 1, msg: '修改成功' });
//         } else {
//             return res.send({ code: 0, msg: '请指定有效的用户' });
//         }
//     } catch (error) {
//         return res.send({ code: 0, msg: error.message });
//     }

// }

var analysisFn = function (req, res, next) {
    var body = req.body || req.query;

    var cmd = parseInt(body.cmd);

    // 命令解析
    if (isNaN(cmd)) {
        return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }

    switch (cmd) {
        case 0:
            getData(req, res, next);
            break;
        case 1:
            requestList.push({ req: req, res: res }); // 单线程程序
            break;
        case 2:
            login(req, res, next);
            break;
        case 3:
            getTableData(req, res);
            break;
        // case 4:
        //     updateUserInfo(req, res);
        //     break;
        default:
            return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }
}

server.post({ path: routerApi, name: routerApi }, analysisFn)